$(function () {

    //Aliases
    let Application = PIXI.Application,
        loader = PIXI.loader,
        resources = PIXI.loader.resources,
        TextureCache = PIXI.utils.TextureCache,
        Sprite = PIXI.Sprite;

    let app = new Application({
            width: 256,         // default: 800
            height: 256,        // default: 600
            antialias: true,    // default: false
            transparent: false, // default: false
            resolution: 1       // default: 1
        }
    );

    $('body').append(app.view);

    // 配置renderer
    app.renderer.backgroundColor = 0x061639;
    app.renderer.autoResize = true;
    app.renderer.resize(512, 512);

    if (false) {
        // 全屏显示
        app.renderer.view.style.position = "absolute";
        app.renderer.view.style.display = "block";
        app.renderer.autoResize = true;
        /*
         $(window).height();                  //浏览器当前窗口可视区域高度
         $(document).height();                //浏览器当前窗口文档的高度
         $(document.body).height();           //浏览器当前窗口文档body的高度
         $(document.body).outerHeight(true);  //浏览器当前窗口文档body的总高度 包括border padding margin
         $(window).width();                   //浏览器当前窗口可视区域宽度
         $(document).width();                 //浏览器当前窗口文档对象宽度
         $(document.body).width();            //浏览器当前窗口文档body的宽度
         $(document.body).outerWidth(true);   //浏览器当前窗口文档body的总宽度 包括border padding margin
         */
        app.renderer.resize(window.innerWidth, window.innerHeight);
    }

    // 资源加载器,可加载单张或多张
    loader
        .add([
            "image/cat.png",
            "image/bunny.png",
            "image/tileset.png"
        ])
        .on("progress", loadProgress)
        .load(setup);

    function loadProgress(loader, resource) {
        console.log("loading..." + resource.url + "..." + loader.progress + "%");
    }

    function setup() {
        console.log("setup");

        let bunny = new Sprite(resources["image/bunny.png"].texture);
        app.stage.addChild(bunny);
        //bunny.visible = false;
        bunny.interactive = true;
        //bunny.scale.set(0.8, 0.8);
        bunny.position.set(bunny.width / 2, bunny.height / 2);
        bunny.pivot.set(bunny.width / 2, bunny.height / 2);
        bunny.rotating = false;
        /*
         1.鼠标左键触发事件：
         click：点击事件
         mousedown：鼠标按下
         mousemove：鼠标移动
         mouseout：鼠标移出
         mouseover：鼠标经过
         mouseup：鼠标松开
         mouseupoutside：鼠标按下，移出对象松开

         2.鼠标右键触发事件：
         rightclick：点击事件
         rightdown：鼠标按下
         rightup：鼠标松开
         rightupoutside：鼠标按下，移出对象松开

         3.触摸屏触发事件：
         touchcancel：触摸系统cancels键
         touchend：触摸结束
         touchendoutside：触摸开始，移出对象松开
         touchmove：触摸移动
         touchstart：触摸开始

         4.兼容鼠标和触摸屏的共同触发：
         pointercancel：触发系统cancels键
         pointerdown：触发按下
         pointermove：触发移动
         pointerout：触发移出
         pointerover：触发经过
         pointertap：触发点击
         pointerup：触发松开
         */
        bunny.on("pointertap", e => {
            bunny.rotating = !bunny.rotating;
        });
        app.ticker.add(t => {
            if (bunny.rotating) {
                bunny.rotation += 0.01;
            }
        });

        let cat = new Sprite(resources["image/cat.png"].texture);
        cat.x = 96;
        cat.y = 96;
        app.stage.addChild(cat);
        //app.stage.removeChild(cat)

        cat.position.set(50, 80);
        //Change the sprite's size
        cat.width = 80;
        cat.height = 120;
        //缩放
        cat.scale.set(1.2, 1.2);
        //旋转
        cat.rotation = 0.5;
        //锚点,图片的旋转中心
        cat.anchor.set(0.5, 0.5);
        //设置精灵的原点,设置好将会围绕着设置的原点来旋转
        //cat.pivot.set(32, 32);

        // anchor改变了精灵纹理的图像原点，用0到1的数据来填充。
        // pivot则改变了精灵的原点，用像素的值来填充。

        // 使用纹理贴图集时给每一个图像增加两个像素的内边距，防止两个图片相邻而相互影响
        // 使用工具：Texture Packer
        //Create the `tileset` sprite from the texture
        let texture = TextureCache["image/tileset.png"];
        //Create a rectangle object that defines the position and
        //size of the sub-image you want to extract from the texture
        //(`Rectangle` is an alias for `PIXI.Rectangle`)
        let rectangle = new PIXI.Rectangle(193, 128, 62, 63);
        //Tell the texture to use that rectangular section
        texture.frame = rectangle;
        texture.baseTexture.scaleMode = PIXI.SCALE_MODES.NEAREST;
        //Create the sprite from the texture
        let rocket = new Sprite(texture);
        //Position the rocket sprite on the canvas
        rocket.x = 32;
        rocket.y = 150;
        rocket.vx = 0;
        //Add the rocket to the stage
        app.stage.addChild(rocket);

        // 给精灵分组
        // let animals = new PIXI.Container();
        // cat.position.set(64, 64);
        // animals.addChild(cat);
        // rocket.position.set(16, 16);
        // animals.addChild(rocket);
        // app.stage.addChild(animals);
        // 获取分组中元素的全局位置
        // animals.toGlobal(cat.position);
        // cat.parent.toGlobal(cat.position);
        // cat.getGlobalPosition().x
        // 找到一个精灵和其他任何一个精灵之间的距离
        // cat.toLocal(cat.position, rocket).x | .y

        // 比在一个普通的Container的渲染速度快2到5倍
        // let superFastSprites = new PIXI.particles.ParticleContainer(
        //     size,
        //     {
        //         rotation: true,
        //         alphaAndtint: true,
        //         scale: true,
        //         uvs: true
        //     }
        // );

        // 绘制几何图形
        let graphics = new PIXI.Graphics();
        graphics.lineStyle(4, 0xFF3300, 1);
        graphics.x = 10;
        graphics.y = 10;

        // 画矩形
        graphics.beginFill(0x66CCFF);
        graphics.drawRect(10, 240, 64, 64);
        graphics.endFill();

        // 画圆角矩形
        graphics.lineStyle(2, 0xFF00FF);
        graphics.beginFill(0xFF00BB, 0.25);
        graphics.drawRoundedRect(380, 120, 100, 100, 15);
        graphics.endFill();
        //app.stage.addChild(graphics);

        //let sp = new Sprite(resources["image/bunny.png"].texture);
        let sp = new Sprite();
        sp.addChild(graphics);
        //cat.rotation = 0.5;
        //sp.scale.set(0.5, 0.5);
        app.stage.addChild(sp);

        // 文本
        let style = new PIXI.TextStyle({
            fontFamily: "Arial",
            fontSize: 36,
            fill: "white",
            stroke: '#ff3300',
            strokeThickness: 4,
            dropShadow: true,
            dropShadowColor: "#000000",
            dropShadowBlur: 4,
            dropShadowAngle: Math.PI / 6,
            dropShadowDistance: 6
        });
        let message = new PIXI.Text("Hello Pixi!", style);
        app.stage.addChild(message);
        message.position.set(200, 350);
        // message.style = style;

        // 多行文本
        //message.style = {wordWrap: true, wordWrapWidth: 100, align: center};

        // 使用CSS字体
        // @font-face {
        //     font-family: "fontFamilyName";
        //     src: url("fonts/fontFile.ttf");
        // }

        app.ticker.add(delta => {
            if (rocket.x < app.view.width - 100) {
                rocket.vx += 0.1;
                rocket.x += rocket.vx;
            }

            cat.rotation += 0.01;
            //console.log(delta);
        });
        // 60 times per second
        //requestAnimationFrame(fn);
    }

    // 碰撞检测
    function hitTestRectangle(r1, r2) {

        //Define the variables we'll need to calculate
        let hit, combinedHalfWidths, combinedHalfHeights, vx, vy;

        //hit will determine whether there's a collision
        hit = false;

        //Find the center points of each sprite
        r1.centerX = r1.x + r1.width / 2;
        r1.centerY = r1.y + r1.height / 2;
        r2.centerX = r2.x + r2.width / 2;
        r2.centerY = r2.y + r2.height / 2;

        //Find the half-widths and half-heights of each sprite
        r1.halfWidth = r1.width / 2;
        r1.halfHeight = r1.height / 2;
        r2.halfWidth = r2.width / 2;
        r2.halfHeight = r2.height / 2;

        //Calculate the distance vector between the sprites
        vx = r1.centerX - r2.centerX;
        vy = r1.centerY - r2.centerY;

        //Figure out the combined half-widths and half-heights
        combinedHalfWidths = r1.halfWidth + r2.halfWidth;
        combinedHalfHeights = r1.halfHeight + r2.halfHeight;

        //Check for a collision on the x axis
        if (Math.abs(vx) < combinedHalfWidths) {

            //A collision might be occuring. Check for a collision on the y axis
            if (Math.abs(vy) < combinedHalfHeights) {

                //There's definitely a collision happening
                hit = true;
            } else {

                //There's no collision on the y axis
                hit = false;
            }
        } else {

            //There's no collision on the x axis
            hit = false;
        }

        //`hit` will be either `true` or `false`
        return hit;
    };

    //生成随机颜色
    function randomColor() {
        var colorStr = Math.floor(Math.random() * 0xFFFFFF).toString(16).toUpperCase();
        return "000000".substring(0, 6 - colorStr) + colorStr;

    }

});